import cv2
import numpy as np

red = (0, 0, 255)


# ==============================
# 最小外接矩阵
# ==============================
def test1():
    #
    src = cv2.imread('graph.png')

    # 转换颜色空间
    img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    # 二值化
    ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    # 查找轮廓
    contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    rect = cv2.minAreaRect(contours[1])
    # 其实就是帮我们把旋转矩阵的4个坐标点计算出来了.
    # 注意坐标必须是整数的, 所以需要转化一下
    box = cv2.boxPoints(rect)
    # 四舍五入
    box = np.round(box).astype('int64')
    # 绘制最小外接矩形
    cv2.drawContours(img, [box], 0, (255, 0, 0), 2)

    cv2.imshow('img_copy', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
